/*
 * G2P_NGram.cpp
 *
 *  Created on: Nov 24, 2012
 *      Author: bannok
 */
#include "g2p_ngram.h"

Darts::DoubleArray bi_gram_da;
prob_bi_struct ** prob_st;
int bi_st_len=0;

int ngram_load(const char* input){
	prob_st = (prob_bi_struct **)calloc(N_GRAM_PROB_MAX,sizeof(prob_bi_struct *));
	FILE * fp = fopen(input,"r");
	if(fp==NULL) return 0;
	while(!feof(fp)){
		prob_bi_struct st ;
		fread(&st,sizeof(prob_bi_struct),1,fp);
		prob_bi_struct * new_st = (prob_bi_struct *)malloc(sizeof(prob_bi_struct));
		new_st->p = st.p;
		new_st->bo = st.bo;
		prob_st[bi_st_len] = new_st;
		bi_st_len++;
	}
	/*
	printf("\ni = %d",prob_st_len);
	for(int i=0;i<prob_st_len;i++){
		printf("%d\t%.4f\t%.4f",i,prob_st[i]->p,prob_st[i]->bo);
		printf("\n");
	}*/
	return 1;
}
int ngram_dict_load(char * fn){
	std::string index = fn;
		if (bi_gram_da.open(index.c_str())) {
			std::cerr << "Error: cannot open " << index << std::endl;
			return -1; // Load Error.
		}
	return 0;
}
int ngram_seach(char * st){
	int re ;
	bi_gram_da.exactMatchSearch(st,re);
	return re;
}
float ngram_calculate(char * st1,char * st2){
//	p(wd2|wd1)= if(bigram exists) p_2(wd1,wd2)
//	            else              bo_wt_1(wd1)*p_1(wd2)
	char tmp[50];
	sprintf(tmp,"%s%s",st1,st2);
	int r1 = ngram_seach(tmp);
	if(r1!=-1){
		return prob_st[r1]->p;
	}else{
		float p1,p2;
		int r2 = ngram_seach(st1);
		int r3 = ngram_seach(st2);
		if(r2!=-1){
			p1 = prob_st[r2]->bo;
		}else{
			r2 = ngram_seach("U");
			p1 = prob_st[r2]->bo;
		}
		if(r3!=-1){
			p2 = prob_st[r3]->p;
		}else{
			r3 = ngram_seach("U");
			p2 = prob_st[r3]->bo;
		}
		return p1+p2;

	}

}



